import React, { useState, useEffect } from "react";
import { Accordion, List, SearchBar } from "antd-mobile";
import "./index.css";
import { requestGetFault } from "../../api/index";

const Home = props => {
  const [list, setList] = useState([]);

  const goDetail = reason => {
    props.history.push("/solution", reason);
  };

  const getDetail = async () => {
    const res = await requestGetFault();
    setList(res);
  };

  const handleChange = value => {
    const filterData = list.map(item => {
      item.hidden = item.name.indexOf(value) > -1 ? false : true;
      return item;
    });

    setList(filterData);
  };

  useEffect(() => {
    getDetail();
  }, []);

  return (
    <div style={{ marginTop: 10, marginBottom: 10 }}>
      <SearchBar placeholder="Search" onChange={handleChange} />
      <Accordion className="my-accordion">
        {list.map(item =>
          !item.hidden ? (
            <Accordion.Panel header={item.name} key={item._id}>
              <List className="my-list">
                {item.reasons.map(reasonItem => (
                  <List.Item
                    arrow="horizontal"
                    onClick={goDetail.bind(null, reasonItem)}
                    key={reasonItem._id}
                    wrap={true}
                  >
                    {reasonItem.name}
                  </List.Item>
                ))}
              </List>
            </Accordion.Panel>
          ) : null
        )}
      </Accordion>
    </div>
  );
};

export default Home;
